# -*- coding: utf-8 -*-
from PIL import ImageGrab
from PyQt5.QtWidgets import QWidget,QVBoxLayout,QLayout,QTextBrowser
from PyQt5.QtCore import Qt
import os
__dir__ = os.path.dirname(os.path.abspath(__file__))
__cache_path__ = os.path.join(__dir__, '../yhd_cache.jpg')

class ControlArea(QWidget):
    position = None
    img = None
    reg = ''
    tran = ''
    control = None

    def __init__(self, control):
        super().__init__()
        self.control = control
        # 取消原生标题栏 | 窗口置顶 | 取消任务栏
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.Tool)
        # 窗体背景透明
        self.setAttribute(Qt.WA_TranslucentBackground, True)
        # 创建透明背景带边框控件
        self.textBrowser = QTextBrowser(self)
        # 设置边框
        self.textBrowser.setStyleSheet("background: transparent;\n"
            "border: 2px dashed blue;")
        # 设置为自适应布局
        self.layout = QVBoxLayout(self)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSizeConstraint(QLayout.SetMaximumSize)
        self.layout.addWidget(self.textBrowser)
        self.setLayout(self.layout)

    # 修改截图区域
    def changeArea(self, pos, size):
        # 缩放比例
        enlarge = 96/96
        self.position = (pos[0]*enlarge, pos[1]*enlarge, (pos[0]+size[0])*enlarge, (pos[1]+size[1])*enlarge)
        self.setFixedSize(size[0], size[1])
        self.move(pos[0], pos[1])
        self.show()
        self.control.showMain()
        self.control.sureArea()

    # 开始截图
    def capturePhoto(self):
        # 左上右下
        self.img = ImageGrab.grab(self.position)
        self.img.save(__cache_path__)
        return self.img

    # 识别
    def regPhoto(self):
        self.reg = self.control.OCR.ocrPath(__cache_path__)
        print(self.reg)
        return self.reg
        
    # 翻译
    def tranPhoto(self):
        word = self.reg
        self.tran = self.control.TRAN.trans(word)
        print(self.tran)
        return self.tran
